# gui/widgets/chat_widget.py
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from datetime import datetime
import json
from gui.styles.style_manager import style_manager

class ChatMessage:
    """聊天消息类"""
    def __init__(self, sender, content, timestamp=None, message_type='text'):
        self.sender = sender  # 'user' 或 'assistant'
        self.content = content
        self.timestamp = timestamp or datetime.now()
        self.message_type = message_type  # 'text', 'command', 'error', 'system'

class ChatDisplayWidget(QWidget):
    """聊天显示组件"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.messages = []
        self.setObjectName("ChatDisplayWidget")
        self.init_ui()

    def init_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 聊天显示区域
        self.chat_display = QTextEdit()
        self.chat_display.setReadOnly(True)
        self.chat_display.setMinimumHeight(150)  # 设置最小高度，移除最大高度限制
        self.chat_display.setLineWrapMode(QTextEdit.WidgetWidth)
        self.chat_display.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.chat_display.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        
        layout.addWidget(self.chat_display)
        
        # 添加欢迎消息
        self.add_system_message("雷达仿真智能体已启动！您可以使用自然语言进行交互。")
        self.add_system_message("例如：'添加一个飞机目标'、'设置雷达功率为2000瓦'、'开始仿真'")
        
    def add_message(self, message: ChatMessage):
        """添加消息"""
        self.messages.append(message)
        self._display_message(message)
        
        # 滚动到底部
        scrollbar = self.chat_display.verticalScrollBar()
        scrollbar.setValue(scrollbar.maximum())
        
    def add_user_message(self, content):
        """添加用户消息"""
        message = ChatMessage('user', content, message_type='command')
        self.add_message(message)
        
    def add_assistant_message(self, content):
        """添加助手回复"""
        message = ChatMessage('assistant', content, message_type='text')
        self.add_message(message)
        
    def add_system_message(self, content):
        """添加系统消息"""
        message = ChatMessage('system', content, message_type='system')
        self.add_message(message)
        
    def add_error_message(self, content):
        """添加错误消息"""
        message = ChatMessage('system', content, message_type='error')
        self.add_message(message)
        
    def _display_message(self, message: ChatMessage):
        """显示消息"""
        timestamp_str = message.timestamp.strftime("%H:%M:%S")

        # 根据消息类型设置颜色和前缀，以及是否需要清理内容
        if message.sender == 'user':
            color = "#58a6ff"
            prefix = "用户"
            # 用户消息只做基本清理，保留原始内容
            content = self._basic_clean_content(message.content)
        elif message.sender == 'assistant':
            color = "#46d164"
            prefix = "助手"
            # 助手消息直接显示，不进行清理
            content = message.content
        else:  # system
            if message.message_type == 'error':
                color = "#f85149"
                prefix = "错误"
            else:
                color = "#79c0ff"
                prefix = "系统"
            # 系统消息直接显示
            content = message.content

        # 使用纯文本格式，更简单可靠
        formatted_message = f"[{timestamp_str}] {prefix}: {content}\n\n"

        # 移动到文档末尾
        cursor = self.chat_display.textCursor()
        cursor.movePosition(QTextCursor.End)

        # 设置字符格式
        char_format = QTextCharFormat()

        # 插入时间戳和角色（使用特殊颜色）
        char_format.setForeground(QColor("#7d8590"))
        char_format.setFont(QFont("Consolas", 9))
        cursor.insertText(f"[{timestamp_str}] ", char_format)

        # 插入角色名（使用角色特定颜色）
        char_format.setForeground(QColor(color))
        char_format.setFont(QFont("Microsoft YaHei", 11, QFont.Bold))
        cursor.insertText(f"{prefix}: ", char_format)

        # 插入内容（使用普通文本颜色，处理换行符）
        char_format.setForeground(QColor("#f0f6fc"))
        char_format.setFont(QFont("Microsoft YaHei", 10))
        char_format.setFontWeight(QFont.Normal)

        # 处理内容中的换行符
        processed_content = content.replace('\\n', '\n')
        cursor.insertText(f"{processed_content}\n", char_format)

        # 设置光标位置并滚动到底部
        self.chat_display.setTextCursor(cursor)

    def _basic_clean_content(self, content):
        """基本的内容清理：保留原始文本"""
        if not content:
            return ""

        # 直接返回原始内容，不做任何处理
        return content.strip()

    def _clean_message_content(self, content):
        """简化的内容清理：只处理基本的文本格式"""
        import re

        if not content:
            return ""

        # 移除emoji符号
        emoji_pattern = re.compile(
            "["
            "\U0001F600-\U0001F64F"  # emoticons
            "\U0001F300-\U0001F5FF"  # symbols & pictographs
            "\U0001F680-\U0001F6FF"  # transport & map symbols
            "\U0001F1E0-\U0001F1FF"  # flags
            "\U00002702-\U000027B0"  # dingbats
            "\U000024C2-\U0001F251"
            "]+",
            flags=re.UNICODE
        )

        cleaned = emoji_pattern.sub('', content).strip()

        # 简单清理：移除开头的指令格式数字
        cleaned = re.sub(r'^\d+[,，]\d+[,，].*?\s+', '', cleaned)
        cleaned = re.sub(r'^["\']?\d+["\']?\s*', '', cleaned)

        # 如果清理后内容太短或只是数字，返回友好消息
        if len(cleaned) < 3 or re.match(r'^[\d\s.,：:-]+$', cleaned):
            return self._generate_friendly_message(content)

        return cleaned.strip()

    def _generate_friendly_message(self, original_content):
        """根据原始内容生成友好的提示消息"""
        content_lower = original_content.lower()

        if any(keyword in content_lower for keyword in ['power', '功率', 'frequency', '频率']):
            return "雷达参数设置完成"
        elif any(keyword in content_lower for keyword in ['目标', 'target', '添加']):
            return "目标操作完成"
        elif any(keyword in content_lower for keyword in ['仿真', '步进', 'simulation']):
            return "仿真操作完成"
        elif any(keyword in content_lower for keyword in ['查询', 'status', '状态']):
            return "状态查询完成"
        elif any(keyword in content_lower for keyword in ['导出', 'export']):
            return "数据导出完成"
        else:
            return "操作完成"
        
    def clear_chat(self):
        """清空聊天记录"""
        self.messages.clear()
        self.chat_display.clear()
        
    def export_chat(self, filename):
        """导出聊天记录"""
        chat_data = []
        for msg in self.messages:
            chat_data.append({
                'sender': msg.sender,
                'content': msg.content,
                'timestamp': msg.timestamp.isoformat(),
                'type': msg.message_type
            })
            
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(chat_data, f, ensure_ascii=False, indent=2)

class ChatInputWidget(QWidget):
    """聊天输入组件"""
    
    # 信号定义
    message_sent = pyqtSignal(str)
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.command_history = []
        self.history_index = -1
        self.setObjectName("ChatInputWidget")
        self.init_ui()
        
    def init_ui(self):
        """初始化UI"""
        layout = QHBoxLayout(self)
        layout.setContentsMargins(8, 4, 8, 4)
        layout.setSpacing(6)
        
        # 输入框
        self.input_line = QLineEdit()
        self.input_line.setPlaceholderText("输入自然语言指令，如：'添加目标在坐标(20,30,5)'...")
        self.input_line.returnPressed.connect(self.send_message)
        
        # 发送按钮
        self.send_btn = QPushButton("发送")
        self.send_btn.setObjectName("SendButton")
        self.send_btn.clicked.connect(self.send_message)
        
        
        # 清空按钮
        self.clear_btn = QPushButton("清空")
        self.clear_btn.setObjectName("ClearButton")
        self.clear_btn.clicked.connect(self.clear_input)
        
        layout.addWidget(self.input_line)
        layout.addWidget(self.send_btn)
        layout.addWidget(self.clear_btn)
        
        # 连接键盘事件
        self.input_line.keyPressEvent = self.handle_key_press
        
    def send_message(self):
        """发送消息"""
        text = self.input_line.text().strip()
        if text:
            self.command_history.append(text)
            self.history_index = len(self.command_history)
            
            self.message_sent.emit(text)
            self.input_line.clear()
            
    def clear_input(self):
        """清空输入"""
        self.input_line.clear()
        
    def set_input_text(self, text):
        """设置输入文本"""
        self.input_line.setText(text)
        self.input_line.setFocus()
        
    def handle_key_press(self, event):
        """处理键盘事件"""
        # 上下箭头键浏览历史命令
        if event.key() == Qt.Key_Up:
            if self.command_history and self.history_index > 0:
                self.history_index -= 1
                self.input_line.setText(self.command_history[self.history_index])
        elif event.key() == Qt.Key_Down:
            if self.command_history and self.history_index < len(self.command_history) - 1:
                self.history_index += 1
                self.input_line.setText(self.command_history[self.history_index])
            elif self.history_index >= len(self.command_history) - 1:
                self.history_index = len(self.command_history)
                self.input_line.clear()
        else:
            # 调用原始的keyPressEvent
            QLineEdit.keyPressEvent(self.input_line, event)

class SmartSuggestionWidget(QWidget):
    """智能建议组件"""
    
    suggestion_selected = pyqtSignal(str)
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.suggestions = [
            "添加目标,飞机1,25,30,5,200,150,0,3.0",
            "设置雷达功率为1500瓦",
            "设置频率为12.5GHz",
            "开始仿真",
            "步进5步",
            "查看仿真状态",
            "清空所有目标",
            "导出数据",
            "添加无人机目标在坐标(15,20,3)",
            "设置天气条件为雨天"
        ]
        self.setObjectName("SmartSuggestionWidget")
        self.init_ui()
        
    def init_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(4)

        # 添加建议按钮
        for suggestion in self.suggestions:
            btn = QPushButton(suggestion)
            btn.setObjectName("SuggestionButton")
            btn.clicked.connect(lambda checked, text=suggestion: self.suggestion_selected.emit(text))
            layout.addWidget(btn)

class ChatPanel(QWidget):
    """完整的聊天面板组件"""

    # 信号定义
    command_executed = pyqtSignal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("ChatPanel")
        self.init_ui()

        # 加载样式
        self.setStyleSheet(style_manager.get_style("chat_widget"))

    def init_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(8, 8, 8, 8)
        layout.setSpacing(6)

        # 面板控制按钮（水平布局）
        control_layout = QHBoxLayout()
        control_layout.setSpacing(4)

        export_btn = QPushButton("导出聊天记录")
        export_btn.setObjectName("ControlPanelButton")
        export_btn.setToolTip("导出聊天记录")
        export_btn.clicked.connect(self.export_chat)

        self.minimize_btn = QPushButton("收起")
        self.minimize_btn.setObjectName("ControlPanelButton")
        self.minimize_btn.clicked.connect(self.toggle_panel)

        control_layout.addWidget(export_btn)
        control_layout.addWidget(self.minimize_btn)

        layout.addLayout(control_layout)

        # 创建主要组件
        self.chat_display = ChatDisplayWidget()
        self.chat_input = ChatInputWidget()
        self.smart_suggestions = SmartSuggestionWidget()

        # 创建智能建议组（带滚动区域）
        self.suggestion_group = QGroupBox("智能建议")
        self.suggestion_group.setObjectName("ChatSuggestionGroup")
        suggestion_main_layout = QVBoxLayout(self.suggestion_group)
        suggestion_main_layout.setContentsMargins(8, 15, 8, 8)

        # 创建滚动区域
        suggestion_scroll = QScrollArea()
        suggestion_scroll.setWidgetResizable(True)
        suggestion_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        suggestion_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        suggestion_scroll.setMinimumHeight(120)  # 最小高度
        suggestion_scroll.setMaximumHeight(300)  # 最大高度
        suggestion_scroll.setWidget(self.smart_suggestions)

        suggestion_main_layout.addWidget(suggestion_scroll)

        # 创建垂直Splitter来分隔聊天显示和智能建议
        self.main_splitter = QSplitter(Qt.Vertical)
        self.main_splitter.setObjectName("ChatMainSplitter")

        # 将组件添加到Splitter
        self.main_splitter.addWidget(self.chat_display)
        self.main_splitter.addWidget(self.suggestion_group)

        # 设置Splitter的初始大小比例 (聊天显示:智能建议 = 2:1)
        self.main_splitter.setSizes([200, 100])
        self.main_splitter.setStretchFactor(0, 2)  # 聊天显示区域可伸缩比例为2
        self.main_splitter.setStretchFactor(1, 1)  # 智能建议区域可伸缩比例为1

        # 添加到主布局
        layout.addWidget(self.main_splitter)
        layout.addWidget(self.chat_input)

        # 连接信号
        self.chat_input.message_sent.connect(self.handle_user_message)
        self.smart_suggestions.suggestion_selected.connect(self.chat_input.set_input_text)

        # 面板状态
        self.is_minimized = False
        
    def handle_user_message(self, message):
        """处理用户消息"""
        self.chat_display.add_user_message(message)
        self.command_executed.emit(message)
        
    def add_assistant_response(self, response):
        """添加助手回复"""
        self.chat_display.add_assistant_message(response)
        
    def add_system_message(self, message):
        """添加系统消息"""
        self.chat_display.add_system_message(message)
        
    def add_error_message(self, message):
        """添加错误消息"""
        self.chat_display.add_error_message(message)
        
    def toggle_panel(self):
        """切换面板显示状态"""
        if self.is_minimized:
            self.main_splitter.show()
            self.minimize_btn.setText("收起")
        else:
            self.main_splitter.hide()
            self.minimize_btn.setText("展开")

        self.is_minimized = not self.is_minimized
        
    def export_chat(self):
        """导出聊天记录"""
        filename, _ = QFileDialog.getSaveFileName(
            self, '导出聊天记录',
            f'chat_log_{datetime.now().strftime("%Y%m%d_%H%M%S")}.json',
            'JSON文件 (*.json)'
        )
        
        if filename:
            self.chat_display.export_chat(filename)
            self.add_system_message(f"聊天记录已导出到: {filename}")
            
    def clear_chat(self):
        """清空聊天记录"""
        self.chat_display.clear_chat()
        self.add_system_message("聊天记录已清空")